<?php
namespace App\Services\Machine;

use App\Services\Mqtt\Publishs;
use Illuminate\Support\Facades\Redis;


/**
 * mqtt
 */
class Setting
{
	public function store($machine)
    {
        $config = $machine->config;
        $setting_data = ["IMEI" => $machine->imei, 'Time' => time(), 'Command' => machine_command('setting')];
        foreach ($config as $key => $value) {
            switch ($value->key) {
                case 'heat':
                    $setting_data['Set_Temp'] = (int)$value->value;
                    $setting_data['Set_Temp_Mode'] = 2;
                    if($value->state == 0){
                        $setting_data['Set_Temp_Mode'] = 0;
                    } 
                    $setting_data['Set_Temp_Ontime'] = string_to_minute($value->start);
                    $setting_data['Set_Temp_Offtime'] = string_to_minute($value->end);
                    break;
                case 'cold':
                    $setting_data['Set_Temp'] = (int)$value->value;
                    $setting_data['Set_Temp_Mode'] = 1;
                    if($value->state == 0){
                        $setting_data['Set_Temp_Mode'] = 0;
                    } 
                    $setting_data['Set_Temp_Ontime'] = string_to_minute($value->start);
                    $setting_data['Set_Temp_Offtime'] = string_to_minute($value->end);
                    break;
                case 'led':
                    $setting_data['Set_Led_Ontime'] = string_to_minute($value->start);
                    $setting_data['Set_Led_Offtime'] = string_to_minute($value->end);
                    $setting_data['Set_Led_Mode'] = $value->state; 
                    break;
            }
        }
        $date['year'] = (int)date('Y');
        $date['month'] = (int)date('m');
        $date['day'] = (int)date('d');
        $date['hour'] = (int)date('H');
        $date['minute'] = (int)date('i');
        $date['second'] = (int)date('s');
        $setting_data['date'] = $date;
        $res = Redis::set('setting:'.$machine->imei, json_encode($setting_data));
        $pub = new Publishs;
        $topic = mqtt_topic('setting',$machine->imei);
        $res = $pub->publish($topic, json_encode($setting_data), 'server_1_laravel5.8');
        $check_data = json_encode(['IMEI' => $machine->imei, 'Command' => machine_command('check'), 'Time' => time()]);
        $pub->publish($topic, $check_data, 'server_1_laravel5.8');
        if(!$res){
            (new MqttLog)->create(['key'=>'setting', 'value' => json_encode($pubData), 'imei' => $machine->imei]);
        }
    }

}